package com.adolph.netty.websocket;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;

/**
 * 〈功能概述〉<br>
 *
 * @author: wangxiangjun
 * @date: 2020-10-14 23:43
 */

public class TextWebSocketFrameHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    private final ChannelGroup group;

    TextWebSocketFrameHandler(ChannelGroup group){
        this.group = group;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
        //增加消息的引用计数
        String temp = "但会！";

            group.writeAndFlush(msg.retain());
    }


    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if(evt == WebSocketServerProtocolHandler.ServerHandshakeStateEvent.HANDSHAKE_TIMEOUT){
            ctx.pipeline().remove(HttpRequestHandler.class);
            //通知所有已经连接的客户端连接上了
            group.writeAndFlush(new TextWebSocketFrame("客户端已经连接"));
            //将新的webSocketChannel添加到ChannelGroup
            group.add(ctx.channel());
        }else{
            super.userEventTriggered(ctx,evt);
        }
    }
}
